import React, { useState, useEffect, forwardRef } from 'react';
import { message, Spin, Select, Row, Col, TreeSelect } from 'antd';

import { size, hasIn, uniqBy } from 'lodash';
import { toArray } from '@/utils/utils';
import { fetchApproveConfig, fetchOrgByUrl } from '../../../../services';

const { Option } = Select;

// 流程设计选择人员、部门等列表选择组件
const OrgListSelect = forwardRef(({ defaultValue = {}, onChange, organizationCode, className, type = 2 }, ref) => {
    const [configData, setConfigData] = useState(null);
    const [typeDynamicData, setTypeDynamicData] = useState({});
    const [loading, setLoading] = useState(false);
    const [typeChangeLoading, setTypeChangeLoading] = useState(false);
    const [outData, setOutData] = useState(defaultValue);

    const [showTreeArr, setShowTreeArr] = useState([]);
    const [selectValue, setSelectValue] = useState();

    const [expandedKeys, setExpandedKeys] = useState([]);

    const getTypeData = () => {
        const arrpro = [];
        const arrKes = [];
        const tempObj = {};
        Object.keys(configData).forEach(key => {
            const item = configData[key];
            const { showTreeFlag } = item;
            tempObj[key] = { showTreeFlag };
            if (item.url !== '') {
                arrpro.push(
                    fetchOrgByUrl({
                        url: item.url,
                        organizationCode
                    })
                );
                arrKes.push(key);
            }
        });

        setShowTreeArr(tempObj);
        setTypeChangeLoading(true);
        Promise.all(arrpro)
            .then(res => {
                const db = {};
                if (arrKes.length > 0) {
                    arrKes.forEach((item, index) => {
                        db[item] = res[index].data;
                    });
                }
                setTypeDynamicData(db);
                setTypeChangeLoading(false);
            })
            .catch(err => {
                message.error(err.message);
                setTypeChangeLoading(false);
            });
    };

    // 获取基础配置信息
    const getConfigData = async () => {
        setLoading(true);
        const { data, code, msg } = await fetchApproveConfig();
        if (code === 10000) {
            setConfigData({ ...data });
        } else {
            setConfigData(null);
            message.error(msg);
        }
        setLoading(false);
    };
    // tree数据格式化
    const getTreeData = data =>
        data.map(item => ({
            ...item,
            value: item.organizationCode,
            title: item.organizationName,
            key: item.organizationCode,
            selectable: !!(item.organizationType === 1 || item.organizationType === 2),
            disableCheckbox: !!(item.organizationType === 1 || item.organizationType === 2),
            children: item.children ? getTreeData(item.children) : item.children
        }));
    // 岗位数据格式化
    const filterDuties = tree =>
        tree.map(i => ({
            title: i.dutyAlias,
            value: i.dutyCode,
            key: i.dutyCode
        }));

    // 机构数据格式化
    const filterTree = tree =>
        tree.map(
            ({
                children,
                organizationName,
                organizationCode: treeOrganizationCode,
                organizationType,
                duties,
                ...props
            }) => {
                if ((children && children.length > 0) || (duties && duties.length > 0)) {
                    return {
                        children: [...filterTree(children), ...filterDuties(duties)],
                        title: organizationName,
                        value: treeOrganizationCode,
                        key: treeOrganizationCode,
                        disabled: false,
                        selectable: false,
                        organizationType,
                        ...props
                    };
                }
                return {
                    children: '',
                    title: organizationName,
                    value: treeOrganizationCode,
                    key: treeOrganizationCode,
                    disabled: !!(!children?.length && !duties?.length),
                    selectable: false, // 不是岗位的都为false
                    organizationType,
                    ...props
                };
            }
        );
    // 岗位、机构数据格式化
    const getTreeProData = tree => {
        const result = filterTree(tree);
        return result;
    };

    // 组件初始化
    useEffect(() => {
        getConfigData();
    }, []);

    useEffect(() => {
        if (configData) {
            getTypeData();
        }
    }, [configData]);

    // 数据回填 showTreeFlag 1 为 树形， 2 为岗位
    useEffect(() => {
        let tempValue = defaultValue;
        let tempExpandedKeys = toArray(defaultValue);
        const tempExpandedKeysObj = {};
        const tempObj = {};

        if (Object.keys(defaultValue).length > 0) {
            Object.keys(defaultValue).forEach(item => {
                if (showTreeArr[item]?.showTreeFlag === 1) {
                    tempValue = defaultValue[item]?.value;
                    tempExpandedKeys = defaultValue[item]?.value.map(subItem => subItem.value);
                }
                if (showTreeArr[item]?.showTreeFlag === 2) {
                    tempValue = defaultValue[item]?.value.map(subItem => subItem.key);
                    tempExpandedKeys = defaultValue[item]?.value.map(subItem => subItem.key);
                }
                tempObj[item] = tempValue;
                tempExpandedKeysObj[item] = tempExpandedKeys;
            });
        }
        setExpandedKeys(size(tempExpandedKeysObj) > 0 ? tempExpandedKeysObj : undefined);
        setSelectValue(size(tempObj) > 0 ? tempObj : undefined);
    }, [defaultValue, showTreeArr]);
    const getChildrenData = datasource => {
        if (size(datasource) > 0) {
            const tempArr = [];
            // 递归获取数据
            const deepFn = node => {
                let obj = node;
                if (hasIn(obj, 'props')) {
                    obj = obj.props;
                }
                tempArr.push({ value: obj?.value, label: obj?.title });
                if (Array.isArray(obj.children)) {
                    obj.children.forEach(item => {
                        deepFn(item);
                    });
                }
            };
            deepFn(datasource);
            return tempArr;
        }
        return [];
    };
    // 渲染 抄送人
    const renderTemp = item => {
        if (showTreeArr[item].showTreeFlag === 1) {
            return (
                <TreeSelect
                    showSearch
                    treeNodeFilterProp="title"
                    placeholder="请选择"
                    value={selectValue && selectValue[item] ? selectValue[item] : undefined}
                    mode="multiple"
                    treeCheckable
                    treeDefaultExpandedKeys={expandedKeys && expandedKeys[item] ? expandedKeys[item] : undefined}
                    treeData={getTreeData(typeDynamicData[item])}
                    style={{ width: '100%' }}
                    dropdownStyle={{ maxHeight: 300 }}
                    maxTagCount={5}
                    allowClear
                    labelInValue
                    treeCheckStrictly
                    onChange={(e = [], label, extra) => {
                        const selectKeys = [];
                        const selectLabels = [];
                        let tempArr = Array.isArray(e) ? e : [e];
                        // const maxSelect = 20;

                        if (extra.checked === true) {
                            tempArr = getChildrenData(extra.triggerNode.props);
                            tempArr = uniqBy([...e, ...tempArr], 'value');
                        }
                        tempArr.forEach(subItem => {
                            selectKeys.push(subItem.value);
                            selectLabels.push(subItem.label);
                        });
                        // if (tempArr.length > maxSelect) {
                        //     message.warn(`最多选择${maxSelect}个`);
                        //     tempArr = tempArr.slice(0, maxSelect);
                        // }
                        const obj = {
                            [item]: {
                                value: tempArr, // 下拉列表的值
                                typeText: configData[item].name, // 类型文本
                                keyVariable: configData[item].keyVariable
                            }
                        };
                        setOutData({ ...outData, ...obj });
                        if (onChange) {
                            onChange({ ...outData, ...obj });
                        }
                    }}
                />
            );
        }
        if (showTreeArr[item].showTreeFlag === 2) {
            return (
                <>
                    <TreeSelect
                        showSearch
                        treeNodeFilterProp="title"
                        value={selectValue && selectValue[item] ? selectValue[item] : undefined}
                        mode="multiple"
                        treeCheckable
                        treeDefaultExpandedKeys={expandedKeys && expandedKeys[item] ? expandedKeys[item] : undefined}
                        treeData={getTreeProData(typeDynamicData[item])}
                        allowClear
                        style={{ width: '100%' }}
                        dropdownStyle={{ maxHeight: 300 }}
                        placeholder="请选择"
                        maxTagCount={5}
                        onChange={(e = [], label) => {
                            const arr = Array.isArray(e) ? e : [e];
                            const formatData = arr.map((subItem, index) => ({ label: label[index], key: subItem }));
                            const obj = {
                                [item]: {
                                    value: formatData, // 下拉列表的值
                                    typeText: configData[item].name, // 类型文本
                                    keyVariable: configData[item].keyVariable
                                }
                            };
                            setOutData({ ...outData, ...obj });
                            if (onChange) {
                                onChange({ ...outData, ...obj });
                            }
                        }}
                    />
                </>
            );
        }
        if (configData[item].url === '') {
            return (
                <Select
                    defaultValue={defaultValue && defaultValue[item] ? defaultValue[item].value : undefined}
                    allowClear
                    labelInValue
                    placeholder="请选择"
                    onChange={async e => {
                        const obj = {
                            [item]: {
                                value: e, // 下拉列表的值
                                typeText: configData[item].name, // 类型文本
                                keyVariable: configData[item].keyVariable
                            }
                        };
                        setOutData({ ...outData, ...obj });
                        if (onChange) {
                            onChange({ ...outData, ...obj });
                        }
                    }}
                >
                    <Option value={1}>是</Option>
                    {type === 2 && <Option value={0}>否</Option>}
                </Select>
            );
        }
        return (
            <Select
                value={defaultValue && defaultValue[item] ? defaultValue[item].value : undefined}
                allowClear
                labelInValue
                mode="multiple"
                placeholder="请选择"
                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                onChange={async e => {
                    let arr = Array.isArray(e) ? e : [e];
                    const maxSelect = 20;
                    if (arr.length > maxSelect) {
                        message.warn(`最多选择${maxSelect}个`);
                        arr = arr.slice(0, maxSelect);
                    }
                    const obj = {
                        [item]: {
                            value: arr, // 下拉列表的值
                            typeText: configData[item].name, // 类型文本
                            keyVariable: configData[item].keyVariable
                        }
                    };
                    setOutData({ ...outData, ...obj });
                    if (onChange) {
                        onChange({ ...outData, ...obj });
                    }
                }}
            >
                {typeDynamicData[item] &&
                    typeDynamicData[item].length > 0 &&
                    typeDynamicData[item]?.map(subItem => (
                        <Option value={subItem[configData[item].keyValue]} key={subItem[configData[item].keyValue]}>
                            {subItem[configData[item].nameValue]}
                        </Option>
                    ))}
            </Select>
        );
    };

    return (
        <div className={className} style={{ overflowX: 'hidden' }} ref={ref}>
            <Spin spinning={loading || typeChangeLoading}>
                {configData &&
                    Object.keys(typeDynamicData).length > 0 &&
                    Object.keys(configData)?.map(
                        item =>
                            configData[item].type.split(',').includes(String(type)) && (
                                <Row key={configData[item].name} gutter={9} style={{ marginBottom: 16 }}>
                                    <Col
                                        span={24}
                                        style={{
                                            textAlign: 'left',
                                            lineHeight: '32px',
                                            fontSize: 12,
                                            fontWeight: 600,
                                            color: '#262626'
                                        }}
                                    >
                                        {configData[item].name}
                                    </Col>
                                    <Col span={24}>{renderTemp(item)}</Col>
                                    <Col span={1}></Col>
                                </Row>
                            )
                    )}
            </Spin>
        </div>
    );
});

export default OrgListSelect;
